package oop.core.med;

import java.util.List;
import java.util.Collection;
import java.util.Map;
import java.util.Iterator;

import oop.core.Scheduler;
import oop.core.Updateable;
import oop.core.entity.*;
import oop.core.area.AreaEffect;
import oop.core.map.Location;


/**
 * This is the mediator that holds the relationship between Area Effects and an Entity.
 */
public class AreaEffectMediator implements Updateable{

	protected Map<Location, AreaEffect> aeMap;
	protected List<Entity> entities;
	protected Entity avatar;
	protected Scheduler sched;
	
	/**
	 * @param aeMap
	 * @param entities
	 */
	public AreaEffectMediator(Map<Location, AreaEffect> aeMap,
			List<Entity> entities, Scheduler sched, Entity avatar) {
		this.aeMap = aeMap;
		this.entities = entities;
		this.sched = sched;
		this.sched.registerPersistent( this );
		this.avatar = avatar;
	}
	
	/**
	 * Checks collisions between entities and Area Effects.
	 * Further, if the AE goes off, the AE is added to the scheduler so the AreaEffect will eventually reactivate.
	 */
	public void checkCollision()
	{
		
		Iterator<Entity> iter = entities.iterator();
		AreaEffect ae;
		
		if(aeMap.containsKey(avatar.getLoc()))
		{
			ae = aeMap.get(avatar.getLoc());
			if(ae.doEffect(avatar))
			{ //If true, then the effect went off.
				sched.register(ae, ae.getDelay());
			}
		}
		
		while(iter.hasNext())
		{
			Entity i = iter.next();
			
			if(aeMap.containsKey(i.getLoc())) //If the entity's location is in the map, eg, there is an entity/AE collision
			{
				ae = aeMap.get(i.getLoc());
				if(ae.doEffect(i))
				{ //If true, then the effect went off.
					sched.register(ae, ae.getDelay());
				}
			}
		}
	}
	
	public void update()
	{
		checkCollision();
	}
	
}


